package tech.aistar.day13;

import tech.aistar.day10.Book;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 本类用来演示: 序列化拓展
 *
 * @author: success
 * @date: 2021/3/24 2:22 下午
 */
@SuppressWarnings("all")
public class ObjectInputStreamExtendsDemo {
    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        Book b1 = new Book(3,"1003","西游记2",100.0d);
        Book b2 = new Book(4,"1004","三体2",100.0d);
        books.add(b1);
        books.add(b2);
//
        writeObj(books,"src/tech/aistar/day13/books.txt");

        List<Book> list = readList("src/tech/aistar/day13/books.txt");
        if(null!=list && list.size()>0){
            for (Book book : list) {
                System.out.println(book);
            }
        }else{
            System.out.println("请先保存数据!");
        }
    }

    public static void writeObj(List<Book> books,String pathname){
        //先读取操作...
        List<Book> oldList = readList(pathname);

        if(oldList!=null && oldList.size()>0){//原来的文件中是存在有效图书数据的
            //oldList中的数据和books新增的集合中的数据 - 整合到一块儿 - 一次性重新写入.
            books.addAll(oldList);
        }

        //1. 构建能够写出对象的字节输出流
        ObjectOutputStream out = null;
        try {
            //覆盖写入,会先将文件中之前的数据清空,然后再写入最新的内容
            //构造 - FileInputStream(String name,boolean append);//true,追加写入...
//            虽然可以解决追加写入了,但是不支持再次读取.
//          序列化和反序列化 - 一定是一次性写,一次性读.不支持分批次写,然后统一去读取.
            //out = new ObjectOutputStream(new FileOutputStream(pathname,true));

            out = new ObjectOutputStream(new FileOutputStream(pathname));

            out.writeObject(books);

            System.out.println("保存成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }if(null!=out){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 对象的反序列化
     * @param pathname
     * @return
     */
    public static List<Book> readList(String pathname){
        List<Book> books = null;

        try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(pathname))){
            books = (List<Book>) in.readObject();
        } catch (FileNotFoundException e) {//如果文件是不存在的...
            //e.printStackTrace();
            //异常处理...
            books = null;
        } catch (IOException e) {
            //1. java.io.EOFException - 读取空文件...
            //2.java.io.StreamCorruptedException - 文件存在,但是文件中的数据是无效的数据
            //e.printStackTrace();
            books = null;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return books;
    }
}
